# -*- coding: utf-8 -*-
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#作者：cacho_37967865
#博客：https://blog.csdn.net/sinat_37967865
#文件：pdf2image_model.py
#日期：2019-10-10
#备注：pip install pdf2image  pdf2image是个包装器，poppler是转换过程真正需要的 
      先下载poppler，解压后把bin目录添加到PATH环境变量里。  配置之后需要重启一下电脑才会生效，不然会错误 
      最后pip install pillow （如果没有安装）  
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

from pdf2image import convert_from_path,convert_from_bytes
import os
import tempfile
import time


def pdf1_to_image(pdfPath, imagePath):
    with tempfile.TemporaryDirectory() as path:
        images_from_path = convert_from_path(pdfPath, output_folder=path,dpi=128,thread_count=4)          # dpi=128 表示为1280*720
        for image in images_from_path:
            if not os.path.exists(imagePath):
                os.makedirs(imagePath)
            image.save(imagePath + '/' + 'output_%02d.jpg' % images_from_path.index(image), 'JPEG')
        #print(images_from_path)


# 这种转换是直接写入到磁盘上的,I/O  需要手动创建文件夹,
def pdf2_to_image(pdfPath, imagePath):
    # output文件夹下形如output_线程id-页码.jpg的一些文件
    convert_from_path(pdfPath, dpi=96,output_folder=imagePath, fmt="JPEG", output_file="output",thread_count=4)


def pdf3_to_image(pdfPath, imagePath):
    images = convert_from_path(pdfPath,dpi=96,thread_count=4)
    for image in images:
        if not os.path.exists(imagePath):
            os.makedirs(imagePath)
        image.save(imagePath + '/' + 'output_%s.jpg' % images.index(image), 'JPEG')


def pdf4_to_image(pdfPath, imagePath):
    images = convert_from_bytes(open(pdfPath, 'rb').read(),dpi=96,thread_count=4)
    for image in images:
        if not os.path.exists(imagePath):
            os.makedirs(imagePath)
        image.save(imagePath + '/' + 'output_%s.jpg' % images.index(image), 'JPEG')


def main(ch):
    sTime = time.time()
    if ch==1:
        pdf1_to_image('F:\\工厂资料.pdf', 'F:\image\\output\\')
    elif ch==2:
        pdf2_to_image('1.pdf', 'F:\image\\output\\')
    elif ch==3:
        pdf3_to_image('1.pdf', 'F:\image\\output\\')
    elif ch==4:
        pdf4_to_image('1.pdf', 'F:\image\\output\\')
    eTime = time.time()
    s = eTime - sTime
    print('花费的时间为：%.2f秒'%(s))


if __name__ == '__main__':
    main(1)



